#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import datetime
import conf
import utils
import utilsj
import counters
import papercomment
import permission
import validator
import xnuser
import paper

class MainPage(webapp.RequestHandler):
    def post(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        isLoggedIn = utils.validateXnCookies(cookieDict, conf.app_secret)
        if not isLoggedIn:
            return self.errorResponse(papercomment.COMMENT_ERROR_CODE_NOT_LOGGED_IN)
        xnuid = cookieDict.get('user')
        try:
            xnuid = int(xnuid)
        except ValueError:
            xnuid = 0

        op = self.request.get('op')
        if op not in ['new', 'del']:
            op = 'new'
        if op == 'del':
            return self.delComment(xnuid)
        else:
            return self.newComment(xnuid)

    def sucessResponse(self, respJson):
        self.response.headers['Content-Type'] = 'application/x-javascript'
        self.response.out.write(utilsj.serializeJson(respJson))
        return None
    def errorResponse(self, errCode):
        self.response.headers['Content-Type'] = 'application/x-javascript'
        respJson = {"errCode": errCode, "errMsg": papercomment.COMMENT_ERROR_MESSAGES[errCode]}
        self.response.out.write(utilsj.serializeJson(respJson))
        return None

    def delComment(self, xnuid):
        commentId = self.request.get('cid')
        try:
            commentId = int(commentId)
        except ValueError:
            commentId = 0
            return self.errorResponse(papercomment.COMMENT_ERROR_CODE_LOSE_PARAMS)
        
        commentModel = papercomment.readPaperCommentById(commentId)
        if not commentModel:
            return self.errorResponse(papercomment.COMMENT_ERROR_CODE_NO_SUCH_COMMENT)
        
        commenterId = commentModel.commenterId
        paperId = commentModel.pid
        paperModel = paper.readPaperById(paperId)
        if not paperModel:
            return self.errorResponse(papercomment.COMMENT_ERROR_CODE_NO_CORRESPONDING_PAPER)
        
        paperAuthorId = paperModel.authorId
        if not permission.hasDeletePaperCommentPermission(xnuid, commenterId, paperAuthorId):
            return self.errorResponse(papercomment.COMMENT_ERROR_CODE_NO_DELETE_PERMISSION)

        #delete the comment from datastore (actually change its status!)
        commentModel.status = papercomment.paperCommentStatusDeleted
        papercomment.writePaperComment(commentModel)

        #return success code!
        return self.errorResponse(papercomment.COMMENT_ERROR_CODE_SUCCESS)

    def newComment(self, xnuid):
        paperId = self.request.get('pid')
        try:
            paperId = int(paperId)
        except ValueError:
            paperId = 0
            return self.errorResponse(papercomment.COMMENT_ERROR_CODE_LOSE_PARAMS)
        comment = self.request.get('pcomment')
        #anti-spam
        commentValidator = validator.PureTextValidator(comment)
        comment = commentValidator.filter()
        #transform line-feed
        comment = comment.replace('\n', '<br/>')
        comment = comment.replace('\r', '')
        #check
        errCode = papercomment.checkPaperComment(comment)
        if errCode != papercomment.COMMENT_ERROR_CODE_SUCCESS:
            return self.errorResponse(errCode)
        
        #save to datastore
        commentModel = papercomment.PaperComment()
        counter = counters.AtomicCounter('pcomment')
        newCid = counter.AtomicInc()
        commentModel.cid = newCid
        commentModel.pid = paperId
        commentModel.commenterId = xnuid
        commentModel.comment = comment
        commentModel.status = papercomment.paperCommentStatusNormal
        papercomment.writePaperComment(commentModel)
        
        #return json info to client
        d = datetime.datetime.today()
        localTime = utils.calculateLocalTime(d)
        xnUserModel = xnuser.getXnUserById(xnuid)
        commenterName = ''
        commenterTinyPhotoUrl = ''
        if xnUserModel:
            commenterName = xnUserModel.name
            commenterTinyPhotoUrl = xnUserModel.tinyurl_with_logo
        respJson = {
            'cid': newCid,
            'pid': paperId,
            'commenterId': xnuid,
            'commenterName': commenterName.encode('utf-8'),
            'commenterPhoto': commenterTinyPhotoUrl.encode('utf-8'),
            'pcomment': comment.encode('utf-8'),
            'time': localTime
        }

        return self.sucessResponse(respJson)

application = webapp.WSGIApplication(
                                     [('/pcomment', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
